<?php 
defined('RUN_KATANA') or die('Restricted access');
class ShopAdmin
{
	public $Commander;
	public $SiteId;
	public $AjaxRun;
	public $ShopSettings;
	public $CurrentMenuId;
	public $CurrentProductId;
	public $CurrentAttributeId;
	public $Info;
	public $Error;
	public $JsActionRun;
	
	public function ShopAdmin()
	{
		global $commander;
		global $shop;
		ini_set("memory_limit","500M");
		$this->Commander = $commander;
		self::setSiteId($commander->SiteId);
		if(defined('AJAX_RUN'))
		{ self::setAjaxRun(true); }
		else
		{ self::setAjaxRun(false); }
		self::runPreActions();
		self::loadShop();
		self::runPostActions();
	}
	
	/* Get Functions */ 
	public function getSiteId() { return $this->SiteId; }
	public function getAjaxRun() { return $this->AjaxRun; }
	public function getShopSettings($setting='') { return $this->ShopSettings; }
	public function getCurrentMenuId() { return intval($this->CurrentMenuId); }
	public function getCurrentProductId() { return intval($this->CurrentProductId); }
	public function getCurrentAttributeId() { return intval($this->CurrentAttributeId); }
	
	/* Set Functions */ 
	public function setSiteId($val) { $this->SiteId=$val; }
	public function setAjaxRun($val) { $this->AjaxRun=$val; }
	public function setShopSettings($val) { $this->ShopSettings=$val; }
	public function setCurrentMenuId($val) { $this->CurrentMenuId=intval($val); }
	public function setCurrentProductId($val) { $this->CurrentProductId=intval($val); }
	public function setCurrentAttributeId($val) { $this->CurrentAttributeId=intval($val); }
	
	function loadShop()
	{
		global $shop;
		self::setShopSettings($shop->getGlobalSettings());
		if(self::getCurrentProductId() > 0)
		{ 
			$shop->setCurrentProductId($this->CurrentProductId); 
			$shop->setView('commander_detail');
			if((intval($_POST['build_variations_all']) > 0) || ($_GET['novars'] > 0))
			{ $shop->loadCurrentProduct(false); }
			else
			{ $shop->loadCurrentProduct(); }
		}
		if(self::getCurrentAttributeId() > 0)
		{ 
			$shop->setCurrentAttributeId(self::getCurrentAttributeId());
			$shop->loadProductAttributes();
		}
		if(self::getCurrentMenuId() > 0)
		{ 
			$shop->setMenuId($this->CurrentMenuId); 
			$shop->setView('commander_list');
			$shop->loadProductsList();
		}
	}
	
	public function runPreActions()
	{
		global $commander;
		global $shop;
		
		if($_REQUEST['item'] > 0)
		{ self::setCurrentProductId($_REQUEST['item']); }
		if($_REQUEST['attribute'] > 0)
		{ self::setCurrentAttributeId($_REQUEST['attribute']); }
		if($_REQUEST['m'] > 0)
		{ self::setCurrentMenuId($_REQUEST['m']); }
		if($_REQUEST['list'] == 'orders')
		{ $shop->loadOrders(); }
		if($_REQUEST['provider'] > 0)
		{ 
			$shop->setCurrentProviderId($_REQUEST['provider']);
			$shop->loadProviders();
		}
		
		switch($_POST['action'])
		{
			case 'product_list':
				if(($_POST['new_product_title'] != '') && ($_REQUEST['m'] > 0))
				{ self::addProduct($_POST['new_product_title'], intval($_REQUEST['m']), '', intval($_POST['new_product_group']), intval($_POST['new_product_cat']), intval($_POST['new_product_tax'])); }
				/*
				if($_POST['up'] > 0)
				{ $commander->setTableItemOrderUp($_POST['up'], 'product', 'product_order', 'section_id'); }
				if($_POST['down'] > 0)
				{ $commander->setTableItemOrderDown($_POST['down'], 'product', 'product_order', 'section_id'); }
				*/
				return;
			break;
			
			case 'editor_product':
				if($_POST['rem_attribute'] > 0)
				{ 
					self::remAttributeFromProduct(self::getCurrentProductId(), $_POST['rem_attribute']); 
					$this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 1 }); ';
				}
				if($_POST['add_attribute'] > 0)
				{ 
					self::addAttributeToProduct(self::getCurrentProductId(), $_POST['add_attribute']);
					$this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 1 }); ';
				}
				return;
			break;
			
			case 'list_shipping':
				if($_POST['activate'] > 0)
				{ $commander->setTableActive($_POST['activate'], 'shop_shipping', 1); }
				if($_POST['deactivate'] > 0)
				{ $commander->setTableActive($_POST['deactivate'], 'shop_shipping', 0); }
				return;
			break;
			
			case 'list_attribute':
				if($_POST['activate'] > 0)
				{ $commander->setTableActive($_POST['activate'], 'product_attributes', 1); }
				if($_POST['deactivate'] > 0)
				{ $commander->setTableActive($_POST['deactivate'], 'product_attributes', 0); }
				if($_POST['del_att_id'] > 0)
				{ self::deleteProductAttribute($_POST['del_att_id']); }
				return;
			break;
			
			case 'editor_attribute':
				if($_POST['up'] > 0)
				{ $commander->setTableItemOrderUp($_POST['up'], 'product_attribute_values', 'value_order', 'attribute_id'); }
				if($_POST['down'] > 0)
				{ $commander->setTableItemOrderDown($_POST['down'], 'product_attribute_values', 'value_order', 'attribute_id'); }
				
				if($_POST['activate'] > 0)
				{ $commander->setTableActive($_POST['activate'], 'product_attribute_values', 1); }
				if($_POST['deactivate'] > 0)
				{ $commander->setTableActive($_POST['deactivate'], 'product_attribute_values', 0); }
				
				if($_POST['visible'] > 0)
				{ $commander->setTableFieldValueOnId('product_attribute_values', 'visible', 1, $_POST['visible']);  }
				if($_POST['invisible'] > 0)
				{ $commander->setTableFieldValueOnId('product_attribute_values', 'visible', 0, $_POST['invisible']);  }
				
				if($_POST['del_att_value_id'] > 0)
				{ self::deleteProductAttributeValue($_POST['del_att_value_id']); }
								
				return;
			break;
			
			case 'list_provider':
				if($_POST['new_provider_title'] != '')
				{ self::addShopProvider($_POST['new_provider_title'], $_POST['new_provider_title_import'], $_POST['new_provider_country'], $_POST['new_provider_city']); }
				if($_POST['activate'] > 0)
				{ $commander->setTableActive($_POST['activate'], 'product_providers', 1); }
				if($_POST['deactivate'] > 0)
				{ $commander->setTableActive($_POST['deactivate'], 'product_providers', 0); }
				if($_POST['del_provider_id'] > 0)
				{ self::deleteShopProvider($_POST['del_provider_id']); }
				$shop->loadProviders();
				return;
			break;
			
			case 'list_brand':
				if($_POST['new_brand_title'] != '')
				{ self::addShopBrand($_POST['new_brand_title'], $_POST['new_brand_title_import'], $_POST['new_brand_country']); }
				if($_POST['activate'] > 0)
				{ $commander->setTableActive($_POST['activate'], 'product_brands', 1); }
				if($_POST['deactivate'] > 0)
				{ $commander->setTableActive($_POST['deactivate'], 'product_brands', 0); }
				if($_POST['del_brand_id'] > 0)
				{ self::deleteShopBrand($_POST['del_brand_id']); }
				$shop->loadBrands();
				return;
			break;
			
			case 'list_group':
				if($_POST['new_group_title'] != '')
				{ self::addProductGroup($_POST['new_group_title'], $_POST['new_group_title_import']); }
				if($_POST['activate'] > 0)
				{ $commander->setTableActive($_POST['activate'], 'product_groups', 1); }
				if($_POST['deactivate'] > 0)
				{ $commander->setTableActive($_POST['deactivate'], 'product_groups', 0); }
				if($_POST['del_group_id'] > 0)
				{ self::deleteProductGroup($_POST['del_group_id']); }
				$shop->loadGroups();
				return;
			break;
			
			case 'list_cat':
				if($_POST['new_cat_title'] != '')
				{ self::addProductCat($_POST['new_cat_title'], $_POST['new_cat_title_import']); }
				if($_POST['activate'] > 0)
				{ $commander->setTableActive($_POST['activate'], 'product_cats', 1); }
				if($_POST['deactivate'] > 0)
				{ $commander->setTableActive($_POST['deactivate'], 'product_cats', 0); }
				if($_POST['del_cat_id'] > 0)
				{ self::deleteProductCat($_POST['del_cat_id']); }
				$shop->loadCats();
				return;
			break;
			
			case 'list_order':
				return;
			break;
		}
	}
	
	public function runPostActions()
	{
		global $db;
		global $commander;
		global $shop;
		switch ($_POST['action'])
		{
			//List-Editor cat actions
			case 'list_cat':
				if((count($_POST['cat_id']) > 0) && ($shop->getCats()))
				{
					$i = 0;
					foreach($_POST['cat_id'] as $id)
					{
						if(isset($shop->Cats[$id]))
						{
							if($_POST['cat_title'][$i] != $shop->Cats[$id]->getTitle())
							{ 
								$shop->Cats[$id]->setTitle($commander->formatText($_POST['cat_title'][$i]));
								$shop->Cats[$id]->setDataChanged(true);
							}
							if($_POST['cat_title_import'][$i] != $shop->Cats[$id]->getTitleImport())
							{ 
								$shop->Cats[$id]->setTitleImport($commander->formatAlias($_POST['cat_title_import'][$i]));
								$shop->Cats[$id]->setDataChanged(true);
							}
							$shop->Cats[$id]->update();
						}
						$i++;
					} //End foreach
					if($_POST['selected'])
					{
						foreach($_POST['selected'] as $id)
						{
							if(isset($shop->Cats[$id]))
							{
								if($_POST['activate'] == '-1')
								{
									$shop->Cats[$id]->setActive(1);
									$commander->setTableActive($id, 'product_cats', 1); 
								}
								if($_POST['deactivate'] == '-1')
								{
									$shop->Cats[$id]->setActive(0);
									$commander->setTableActive($id, 'product_cats', 0); 
								}
							}
						}
					}
				}
			break;
			//List-Editor cat actions end
			
			//List-Editor group actions
			case 'list_group':
				if((count($_POST['group_id']) > 0) && ($shop->getGroups()))
				{
					$i = 0;
					foreach($_POST['group_id'] as $id)
					{
						if(isset($shop->Groups[$id]))
						{
							if($_POST['group_title'][$i] != $shop->Groups[$id]->getTitle())
							{ 
								$shop->Groups[$id]->setTitle($commander->formatText($_POST['group_title'][$i]));
								$shop->Groups[$id]->setDataChanged(true);
							}
							if($_POST['group_title_import'][$i] != $shop->Groups[$id]->getTitleImport())
							{ 
								$shop->Groups[$id]->setTitleImport($commander->formatAlias($_POST['group_title_import'][$i]));
								$shop->Groups[$id]->setDataChanged(true);
							}
							else
							{
								if($shop->Groups[$id]->getTitleImport() == '')
								{
									$shop->Groups[$id]->setTitleImport($commander->formatAlias($shop->Groups[$id]->getTitle()));
									$shop->Groups[$id]->setDataChanged(true);
								}
							}
							$shop->Groups[$id]->update();
						}
						$i++;
					} //End foreach
					if($_POST['selected'])
					{
						foreach($_POST['selected'] as $id)
						{
							if(isset($shop->Groups[$id]))
							{
								if($_POST['activate'] == '-1')
								{
									$shop->Groups[$id]->setActive(1);
									$commander->setTableActive($id, 'product_groups', 1); 
								}
								if($_POST['deactivate'] == '-1')
								{
									$shop->Groups[$id]->setActive(0);
									$commander->setTableActive($id, 'product_groups', 0); 
								}
							}
						}
					}
				}
			break;
			//List-Editor group actions end
			
			//List-Editor brand actions
			case 'list_brand':
				if((count($_POST['brand_id']) > 0) && ($shop->getBrands()))
				{
					$i = 0;
					foreach($_POST['brand_id'] as $id)
					{
						if(isset($shop->Brands[$id]))
						{
							if($_POST['brand_title'][$i] != $shop->Brands[$id]->getTitle())
							{ 
								$shop->Brands[$id]->setTitle($commander->formatText($_POST['brand_title'][$i]));
								$shop->Brands[$id]->setDataChanged(true);
							}
							if($_POST['brand_title_import'][$i] != $shop->Brands[$id]->getTitleImport())
							{ 
								$shop->Brands[$id]->setTitleImport($commander->formatAlias($_POST['brand_title_import'][$i]));
								$shop->Brands[$id]->setDataChanged(true);
							}
							else
							{
								if($shop->Brands[$id]->getTitleImport() == '')
								{
									$shop->Brands[$id]->setTitleImport($commander->formatAlias($shop->Brands[$id]->getTitle()));
									$shop->Brands[$id]->setDataChanged(true);
								}
							}
							if($_POST['brand_country'][$i] != $shop->Brands[$id]->getCountry())
							{ 
								$shop->Brands[$id]->setCountry($commander->formatText($_POST['brand_country'][$i]));
								$shop->Brands[$id]->setDataChanged(true);
							}
							$shop->Brands[$id]->update();
						}
						$i++;
					} //End foreach
					if($_POST['selected'])
					{
						foreach($_POST['selected'] as $id)
						{
							if(isset($shop->Brands[$id]))
							{
								if($_POST['activate'] == '-1')
								{
									$shop->Brands[$id]->setActive(1);
									$commander->setTableActive($id, 'product_brands', 1); 
								}
								if($_POST['deactivate'] == '-1')
								{
									$shop->Brands[$id]->setActive(0);
									$commander->setTableActive($id, 'product_brands', 0); 
								}
							}
						}
					}
				}
			break;
			//List-Editor brand actions end
			//List-Editor provider actions
			case 'list_provider':
				if((count($_POST['provider_id']) > 0) && ($shop->getProviders()))
				{
					$i = 0;
					foreach($_POST['provider_id'] as $id)
					{
						if(isset($shop->Providers[$id]))
						{
							if($_POST['provider_title'][$i] != $shop->Providers[$id]->getTitle())
							{ 
								$shop->Providers[$id]->setTitle($commander->formatText($_POST['provider_title'][$i]));
								$shop->Providers[$id]->setDataChanged(true);
							}
							if($_POST['provider_title_import'][$i] != $shop->Providers[$id]->getTitleImport())
							{ 
								$shop->Providers[$id]->setTitleImport($commander->formatAlias($_POST['provider_title_import'][$i]));
								$shop->Providers[$id]->setDataChanged(true);
							}
							else
							{
								if($shop->Providers[$id]->getTitleImport() == '')
								{
									$shop->Providers[$id]->setTitleImport($commander->formatAlias($shop->Providers[$id]->getTitle()));
									$shop->Providers[$id]->setDataChanged(true);
								}
							}
							if($_POST['provider_city'][$i] != $shop->Providers[$id]->getCity())
							{ 
								$shop->Providers[$id]->setCity($commander->formatText($_POST['provider_city'][$i]));
								$shop->Providers[$id]->setDataChanged(true);
							}
							if($_POST['provider_zip'][$i] != $shop->Providers[$id]->getZip())
							{ 
								$shop->Providers[$id]->setZip($commander->formatText($_POST['provider_zip'][$i]));
								$shop->Providers[$id]->setDataChanged(true);
							}
							if($_POST['provider_country'][$i] != $shop->Providers[$id]->getCountry())
							{ 
								$shop->Providers[$id]->setCountry($commander->formatText($_POST['provider_country'][$i]));
								$shop->Providers[$id]->setDataChanged(true);
							}
							if($_POST['provider_email'][$i] != $shop->Providers[$id]->getEmail())
							{ 
								$shop->Providers[$id]->setEmail($commander->formatText($_POST['provider_email'][$i]));
								$shop->Providers[$id]->setDataChanged(true);
							}
							if($_POST['provider_tel'][$i] != $shop->Providers[$id]->getTel())
							{ 
								$shop->Providers[$id]->setTel($commander->formatText($_POST['provider_tel'][$i]));
								$shop->Providers[$id]->setDataChanged(true);
							}
							$shop->Providers[$id]->update();
						}
						$i++;
					} //End foreach
					if($_POST['selected'])
					{
						foreach($_POST['selected'] as $id)
						{
							if(isset($shop->Providers[$id]))
							{
								if($_POST['activate'] == '-1')
								{
									$shop->Providers[$id]->setActive(1);
									$commander->setTableActive($id, 'product_providers', 1); 
								}
								if($_POST['deactivate'] == '-1')
								{
									$shop->Providers[$id]->setActive(0);
									$commander->setTableActive($id, 'product_providers', 0); 
								}
							}
						}
					}
				}
			break;
			//List-Editor provider actions end
			//Editor provider actions
			case 'editor_provider':
				if((is_object($shop->getCurrentProvider())) && ($shop->getCurrentProviderId() > 0))
				{
					if(stripslashes($_POST['title']) !== $shop->CurrentProvider->getTitle())
					{ 
						$shop->CurrentProvider->setTitle($commander->formatText($_POST['title'])); 
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['title_import']) != $shop->CurrentProvider->getTitleImport())
					{ 
						$shop->CurrentProvider->setTitleImport($commander->formatAlias($_POST['title_import']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['contact']) != $shop->CurrentProvider->getContact())
					{ 
						$shop->CurrentProvider->setContact($commander->formatText($_POST['contact']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['address']) != $shop->CurrentProvider->getAddress())
					{ 
						$shop->CurrentProvider->setAddress($commander->formatText($_POST['address']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['zip']) !== $shop->CurrentProvider->getZip())
					{ 
						$shop->CurrentProvider->setZip($commander->formatText($_POST['zip']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['city']) != $shop->CurrentProvider->getCity())
					{ 
						$shop->CurrentProvider->setCity($commander->formatText($_POST['city']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['country']) != $shop->CurrentProvider->getCountry())
					{ 
						$shop->CurrentProvider->setCountry($commander->formatText($_POST['country']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['email']) != $shop->CurrentProvider->getEmail())
					{ 
						if($commander->isEmail($_POST['email']))
						{
							$shop->CurrentProvider->setEmail($commander->formatText($_POST['email']));
							$shop->CurrentProvider->setDataChanged(true);
						}
						else
						{ $commander->addError('email', 'Invalid e-mail format'); }
					}
					if(stripslashes($_POST['tel']) !== $shop->CurrentProvider->getTel())
					{ 
						$shop->CurrentProvider->setTel($commander->formatText($_POST['tel']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['fax']) !== $shop->CurrentProvider->getFax())
					{ 
						$shop->CurrentProvider->setFax($commander->formatText($_POST['fax']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['homepage']) != $shop->CurrentProvider->getHomepage())
					{ 
						$shop->CurrentProvider->setHomepage($commander->formatText($_POST['homepage']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					if(stripslashes($_POST['description']) != $shop->CurrentProvider->getDescription())
					{ 
						$shop->CurrentProvider->setDescription($commander->formatText($_POST['description']));
						$shop->CurrentProvider->setDataChanged(true);
					}
					
					
					if(intval($_POST['add_brand_id']) > 0)
					{  $shop->CurrentProvider->addBrand(intval($_POST['add_brand_id'])); }
					if(intval($_POST['rem_brand_id']) > 0)
					{ $shop->CurrentProvider->remBrand(intval($_POST['rem_brand_id'])); }
					
					if(intval($_POST['add_group_id']) > 0)
					{  $shop->CurrentProvider->addGroup(intval($_POST['add_group_id'])); }
					if(intval($_POST['rem_group_id']) > 0)
					{  $shop->CurrentProvider->remGroup(intval($_POST['rem_group_id'])); }
					
					$shop->CurrentProvider->Update();
				}
			break;	
			//Editor provider actions end
			
			case 'list_attribute':
				if($_POST['new_atr'][0] != '')
				{ 
					self::addProductAttribute($_POST['new_atr'][0]);
					$shop->setProductAttributesLoaded(false);
				}
				if((count($_POST['attr_id']) > 0) && ($shop->getProductAttributes()))
				{
					$i = 0;
					foreach($_POST['attr_id'] as $id)
					{
						if(isset($shop->ProductAttributes[$id]))
						{
							if($_POST['attr_title'][$i] != $shop->ProductAttributes[$id]->getTitle())
							{ 
								$shop->ProductAttributes[$id]->setTitle($commander->formatText($_POST['attr_title'][$i]));
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							if($_POST['attr_title_import'][$i] != $shop->ProductAttributes[$id]->getTitleImport())
							{ 
								$shop->ProductAttributes[$id]->setTitleImport(strtolower($commander->formatAlias($_POST['attr_title_import'][$i])));
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							if($_POST['attr_effect'][$i] != $shop->ProductAttributes[$id]->getEffect())
							{ 
								$shop->ProductAttributes[$id]->setEffect($_POST['attr_effect'][$i]);
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							if($_POST['attr_effect_image'][$i] != $shop->ProductAttributes[$id]->getEffectImage())
							{ 
								$shop->ProductAttributes[$id]->setEffectImage($_POST['attr_effect_image'][$i]);
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							if($_POST['attr_val_types'][$i] != $shop->ProductAttributes[$id]->getValTypes())
							{ 
								$shop->ProductAttributes[$id]->setValTypes($_POST['attr_val_types'][$i]);
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							if($_POST['attr_predefined'][$i] != $shop->ProductAttributes[$id]->getPredefined())
							{ 
								$shop->ProductAttributes[$id]->setPredefined($_POST['attr_predefined'][$i]);
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							if($_POST['attr_type'][$i] != $shop->ProductAttributes[$id]->getType())
							{ 
								$shop->ProductAttributes[$id]->setType($_POST['attr_type'][$i]);
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							if($_POST['attr_display'][$i] != $shop->ProductAttributes[$id]->getDisplay())
							{ 
								$shop->ProductAttributes[$id]->setDisplay($_POST['attr_display'][$i]);
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							if($_POST['attr_display_list'][$i] != $shop->ProductAttributes[$id]->getDisplayList())
							{ 
								$shop->ProductAttributes[$id]->setDisplayList($_POST['attr_display_list'][$i]);
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							if($_POST['attr_display_all'][$i] != $shop->ProductAttributes[$id]->getDisplayAll())
							{ 
								$shop->ProductAttributes[$id]->setDisplayAll($_POST['attr_display_all'][$i]);
								$shop->ProductAttributes[$id]->setDataChanged(true);
							}
							$shop->ProductAttributes[$id]->update();
						}
						$i++;
					}
				}
			break;	
			
			case 'editor_attribute':
				if((is_object($shop->CurrentAttribute)) && (self::getCurrentAttributeId() > 0))
				{
					if($shop->CurrentAttribute->getPredefined() > 0)
					{
						if($_POST['new_att_value'][0] != '')
						{ 
							self::addProductAttributeValue($_POST['new_att_value'][0]);
							$shop->CurrentAttribute->setValuesLoaded(false);
						}
						if(count($_POST['val_id']) > 0)
						{
							$i = 0;
							foreach($_POST['val_id'] as $id)
							{
								if(isset($shop->CurrentAttribute->Values[$id]))
								{
									if($_POST['val_value'][$i] != $shop->CurrentAttribute->Values[$id]->getValue())
									{ 
										$shop->CurrentAttribute->Values[$id]->setValue($commander->formatText($_POST['val_value'][$i]));
										$shop->CurrentAttribute->Values[$id]->setDataChanged(true);
									}
									if($_POST['val_postfix'][$i] != $shop->CurrentAttribute->Values[$id]->getPostfix())
									{ 
										$shop->CurrentAttribute->Values[$id]->setPostfix($commander->formatText($_POST['val_postfix'][$i]));
										$shop->CurrentAttribute->Values[$id]->setDataChanged(true);
									}
									if($_POST['val_postfix_position'][$i] != $shop->CurrentAttribute->Values[$id]->getPostfixPosition())
									{ 
										$shop->CurrentAttribute->Values[$id]->setPostfixPosition($commander->formatText($_POST['val_postfix_position'][$i]));
										$shop->CurrentAttribute->Values[$id]->setDataChanged(true);
									}
									if((is_numeric($_POST['val_price'][$i])) && ($_POST['val_price'][$i] != $shop->CurrentAttribute->Values[$id]->getValuePrice()))
									{ 
										$shop->CurrentAttribute->Values[$id]->setValuePrice($commander->formatPrice($_POST['val_price'][$i])); 
										$shop->CurrentAttribute->Values[$id]->setDataChanged(true);
									}
									$shop->CurrentAttribute->Values[$id]->update();
								}
								$i++;
							}
							if($_POST['selected'])
							{
								foreach($_POST['selected'] as $id)
								{
									if(isset($shop->CurrentAttribute->Values[$id]))
									{
										if($_POST['activate'] == '-1')
										{
											$shop->CurrentAttribute->Values[$id]->setActive(1);
											$commander->setTableActive($id, 'product_attribute_values', 1); 
										}
										if($_POST['deactivate'] == '-1')
										{
											$shop->CurrentAttribute->Values[$id]->setActive(0);
											$commander->setTableActive($id, 'product_attribute_values', 0); 
										}
									}
								}
							}
						}
						$shop->CurrentAttribute->loadValues();
					}
				}
			break;	
			
			case 'list_order':
				if(isset($shop->Orders))
				{
					/* Subitems list actions */
					if(count($_POST['o_id']) > 0)
					{
						$i=0;
						foreach($_POST['o_id'] as $id)
						{
							if(isset($shop->Orders[$id]))
							{
								
								if($shop->Orders[$id]->getDeliveryStatus() != intval($_POST['o_delivery_status_'.$id]))
								{ 
									$info = $shop->changeOrderDeliveryStatus($id, intval($_POST['o_delivery_status_'.$id]));
									if($info['error'])
									{ $this->Error = $info['error']; }
									if($info['sucess'] == true)
									{ $this->Info = $info['info']; }
								}
								if($_POST['export_order'] == $shop->Orders[$id]->getId())
								{ 
									echo 'Exporting:';
									if($shop->Orders[$id]->exportOrder() > 0)
									{ echo 'Sucess<br />'; }
								}
							}
							$i++;
						}
						if(($_POST['delete_order'] > 0) && (isset($shop->Orders[$_POST['delete_order']])))
						{ 
							if($shop->deleteOrder($_POST['delete_order']))
							{ unset($shop->ProductList[$_POST['delete_order']]); }
						}
					}
				}
			break;
			
			case 'product_list':
				if(isset($shop->ProductList))
				{
					/* Subitems list actions */
					if(count($_POST['p_id']) > 0)
					{
						$i=0;
						$upDown = 0;
						foreach($_POST['p_id'] as $id)
						{
							$up = 0;
							$down = 0;
							if($commander->formatText($_POST['p_title'][$i]) != $shop->ProductList[$id]->getTitle())
							{ 
								$shop->ProductList[$id]->setTitle($commander->formatText($_POST['p_title'][$i]));
								$shop->ProductList[$id]->setAlias($commander->formatAlias($_POST['p_title'][$i]));
								$shop->ProductList[$id]->setDataChanged(true);
							}
							if(($shop->getGlobalSetting('groups')) && ($_POST['p_group_id'][$i] != $shop->ProductList[$id]->getGroupId()))
							{ 
								$shop->ProductList[$id]->setGroupId($_POST['p_group_id'][$i]);
								$shop->ProductList[$id]->setDataChanged(true);
							}
							if(($shop->getGlobalSetting('categories')) && ($_POST['p_cat_id'][$i] != $shop->ProductList[$id]->getCatId()))
							{ 
								$shop->ProductList[$id]->setCatId(intval($_POST['p_cat_id'][$i]));
								$shop->ProductList[$id]->setDataChanged(true);
							}
							if(($shop->getGlobalSetting('use_tax')) && (intval($_POST['p_tax_id'][$i]) != $shop->ProductList[$id]->getTaxId()))
							{ 
								$shop->ProductList[$id]->setTaxId(intval($_POST['p_tax_id'][$i]));
								$shop->ProductList[$id]->setDataChanged(true);
							}
							if(($shop->getGlobalSetting('simple_price_model')) && (intval($_POST['p_price'][$i]) != $shop->ProductList[$id]->getPrice()))
							{ 
								$shop->ProductList[$id]->setPrice(intval($_POST['p_price'][$i]));
								$shop->ProductList[$id]->setDataChanged(true);
							}
							if(intval($_POST['FrontpageDisplay'][$i]) != $shop->ProductList[$id]->getFrontpageDisplay())
							{ 
								$shop->ProductList[$id]->setFrontpageDisplay(intval($_POST['FrontpageDisplay'][$i]));
								$shop->ProductList[$id]->setDataChanged(true);
							}
							if(intval($_POST['ProductOrder'][$i]) != $shop->ProductList[$id]->getProductOrder())
							{ 
								$shop->ProductList[$id]->setProductOrder(intval($_POST['ProductOrder'][$i]));
								$shop->ProductList[$id]->setDataChanged(true);
								if(intval($_POST['ProductOrder'][$i]) > $shop->ProductList[$id]->getProductOrder())
								{ $down = $id; }
								if(intval($_POST['ProductOrder'][$i]) < $shop->ProductList[$id]->getProductOrder())
								{ $up = $id; }
								$upDown++;
							}
							if($shop->getGlobalSetting('product_sale_hours'))
							{
								if(intval($_POST['SaleStartHour'][$i]) != $shop->ProductList[$id]->getSaleStartHour())
								{ 
									$shop->ProductList[$id]->setSaleStartHour(intval($_POST['SaleStartHour'][$i]));
									$shop->ProductList[$id]->setDataChanged(true);
								}
								if(intval($_POST['SaleEndHour'][$i]) != $shop->ProductList[$id]->getSaleEndHour())
								{ 
									$shop->ProductList[$id]->setSaleEndHour(intval($_POST['SaleEndHour'][$i]));
									$shop->ProductList[$id]->setDataChanged(true);
								}
							}
							if($shop->getGlobalSetting('variations') == false)
							{
								$variation = $shop->ProductList[$id]->Variations[$shop->ProductList[$id]->getFirstVariationId()];
								if($_POST['var_title'][$i] != $variation->getVarTitle())
								{ 
									$variation->setVarTitle($commander->formatText($_POST['var_title'][$i]));
									$variation->setDataChanged(true);
								}
								if($_POST['identity'][$i] != $variation->getIdentity())
								{ 
									$variation->setIdentity($commander->formatText($_POST['identity'][$i]));
									$variation->setDataChanged(true);
								}
								if($_POST['ext_identity'][$i] != $variation->getExtIdentity())
								{ 
									$variation->setExtIdentity($commander->formatText($_POST['ext_identity'][$i]));
									$variation->setDataChanged(true);
								}
								if($shop->GlobalSettings['shipping_weight_volume_active'])
								{
									if(intval($_POST['length'][$i]) != $variation->getLength())
									{ 
										$variation->setLength(intval($_POST['length'][$i])); 
										$variation->setDataChanged(true);
									}
									if(intval($_POST['width'][$i]) != $variation->getWidth())
									{ 
										$variation->setWidth(intval($_POST['width'][$i])); 
										$variation->setDataChanged(true);
									}
									if(intval($_POST['height'][$i]) != $variation->getHeight())
									{ 
										$variation->setHeight(intval($_POST['height'][$i])); 
										$variation->setDataChanged(true);
									}
								}
								$variation->update();
							}
							$shop->ProductList[$id]->update();
							
							if($up > 0)
							{ $commander->setTableItemOrderUp($up, 'product', 'product_order', 'section_id'); $upDown++; }
							if($down > 0)
							{ $commander->setTableItemOrderDown($down, 'product', 'product_order', 'section_id'); $upDown++; }
							$i++;
						}
						//print_r($_POST);
						if(($_POST['activate'] > 0) && (isset($shop->ProductList[$_POST['activate']])))
						{ 
							$shop->ProductList[$_POST['activate']]->setActive(1);
							$commander->setTableActive($_POST['activate'], 'product', 1); 
						}
						if(($_POST['deactivate'] > 0) && (isset($shop->ProductList[$_POST['deactivate']])))
						{ 
							$shop->ProductList[$_POST['deactivate']]->setActive(0);
							$commander->setTableActive($_POST['deactivate'], 'product', 0);  
						}
						if(($_POST['delete_p'] > 0) && (isset($shop->ProductList[$_POST['delete_p']])))
						{ 
							if(self::deleteProduct($_POST['delete_p']))
							{ unset($shop->ProductList[$_POST['delete_p']]); }
						}
						if($_POST['selected'])
						{
							foreach($_POST['selected'] as $id)
							{
								if(isset($shop->ProductList[$id]))
								{
									if($_POST['activate'] == '-1')
									{
										$shop->ProductList[$id]->setActive(1);
										$commander->setTableActive($id, 'product', 1); 
									}
									if($_POST['deactivate'] == '-1')
									{
										$shop->ProductList[$id]->setActive(0);
										$commander->setTableActive($id, 'product', 0); 
									}
								}
							}
						}
						if($upDown > 0)
						{
							unset($shop->ProductList);
							$shop->loadProductsList();
						}
					}
				}
			break;
			
			case 'editor_product':
				if(isset($shop->CurrentProduct))
				{	
					if($shop->CurrentProduct->getAttributesVar() && (intval($_POST['build_variations_all']) > 0))
					{ self::buildAllVariations(); }
					
					if($shop->CurrentProduct->getAttributesVar() && (intval($_POST['build_variatons_on_att']) > 0))
					{ self::buildVariationsOnAtt(intval($_POST['build_variatons_on_att'])); }
					
					if($_POST['new_var'] != '')
					{ 
						$shop->CurrentProduct->addVariation($commander->formatText($_POST['new_var']), $_POST['new_var_identity']);
						$this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 3 }); ';
					}
					
					/* Item field actions */
					if(stripslashes($_POST['title']) !== $shop->CurrentProduct->getTitle())
					{ 
						$shop->CurrentProduct->setTitle($commander->formatText($_POST['title'])); 
						$shop->CurrentProduct->setAlias($commander->formatAlias($shop->CurrentProduct->getTitle()));
						$shop->CurrentProduct->setDataChanged(true);
					}
					if(stripslashes($_POST['intro']) !== $shop->CurrentProduct->getIntro())
					{ 
						if($shop->getSetting('list_view_editor') > 0)
						{ $shop->CurrentProduct->setIntro($_POST['intro']); }
						else
						{ $shop->CurrentProduct->setIntro($commander->formatText($_POST['intro'])); }
						$shop->CurrentProduct->setDataChanged(true);
					}
					if(stripslashes($_POST['Description']) !== $shop->CurrentProduct->getDescription())
					{ 
						$shop->CurrentProduct->setDescription($_POST['Description']); 
						$shop->CurrentProduct->setDataChanged(true);
						$this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 0 }); ';
					}
					if($shop->getGlobalSetting('detail_txt'))
					{
						if(stripslashes($_POST['details']) != $shop->CurrentProduct->getDetails())
						{ 
							$shop->CurrentProduct->setDetails($_POST['details']); 
							$shop->CurrentProduct->setDataChanged(true);
							$this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 0 }); ';
						}
					}
					if($shop->getGlobalSetting('use_stock_units'))
					{
						if(stripslashes($_POST['stock_unit']) != $shop->CurrentProduct->getStockUnit())
						{ 
							$shop->CurrentProduct->setStockUnit($commander->formatText($_POST['stock_unit'])); 
							$shop->CurrentProduct->setDataChanged(true);
						}
					}
					if($shop->getGlobalSetting('use_dim_shipping_calculation'))
					{
						if(stripslashes($_POST['weight_unit']) !== $shop->CurrentProduct->getWeightUnit())
						{ 
							$shop->CurrentProduct->setWeightUnit($commander->formatText($_POST['weight_unit'])); 
							$shop->CurrentProduct->setDataChanged(true);
						}
						if(stripslashes($_POST['dim_unit']) !== $shop->CurrentProduct->getDimUnit())
						{ 
							$shop->CurrentProduct->setDimUnit($commander->formatText($_POST['dim_unit'])); 
							$shop->CurrentProduct->setDataChanged(true);
						}
					}
					if(($shop->getGlobalSetting('brand')) && (intval($_POST['brand']) != $shop->CurrentProduct->getBrand()))
					{ 
						$shop->CurrentProduct->setBrand(intval($_POST['brand'])); 
						$shop->CurrentProduct->setDataChanged(true);
					}
					if(($shop->getGlobalSetting('provider')) && (intval($_POST['provider']) != $shop->CurrentProduct->getProvider()))
					{ 
						$shop->CurrentProduct->setProvider(intval($_POST['brand'])); 
						$shop->CurrentProduct->setDataChanged(true);
					}
					if(($shop->getGlobalSetting('categories')) && (intval($_POST['cat_id']) != $shop->CurrentProduct->getCatId()))
					{ 
						$shop->CurrentProduct->setCatId(intval($_POST['cat_id'])); 
						$shop->CurrentProduct->setDataChanged(true);
					}
					if(($shop->getGlobalSetting('groups')) && (intval($_POST['group_id']) != $shop->CurrentProduct->getGroupId()))
					{ 
						$shop->CurrentProduct->setGroupId(intval($_POST['group_id'])); 
						$shop->CurrentProduct->setDataChanged(true);
					}
					if((intval($_POST['tax_id']) > 0) && (intval($_POST['tax_id']) != $shop->CurrentProduct->getTaxId()))
					{ 
						$shop->CurrentProduct->setTaxId(intval($_POST['tax_id'])); 
						$shop->CurrentProduct->setDataChanged(true);
					}
					if($_POST['price_tax_excl'] != $shop->CurrentProduct->getPrice())
					{ 
						$shop->CurrentProduct->setPrice($commander->formatPrice($_POST['price_tax_excl'])); 
						$shop->CurrentProduct->setDataChanged(true);
					}
					if($_POST['active'] != $shop->CurrentProduct->getActive())
					{ 
						$shop->CurrentProduct->setActive($_POST['active']); 
						$shop->CurrentProduct->setDataChanged(true);
					}
					if($_POST['act_date'] != '')
					{
						$ActiveStart		= mktime(0,0,0,0,0,0);
						$ActiveStart = mktime(intval($_POST['act_hh']), 0, 0, abs(substr($_POST['act_date'], 5, 2)), abs(substr($_POST['act_date'], 8, 2)),  substr($_POST['act_date'], 0, 4));
						if(date("Y-m-d H:i:s",$ActiveStart) != $shop->CurrentProduct->ActiveStart)
						{
							$shop->CurrentProduct->setActiveStart(date("Y-m-d H:i:s",$ActiveStart));
							$shop->CurrentProduct->setDataChanged(true);
						}
					}
					if($_POST['deac_date'] != '')
					{
						$ActiveEnd		= mktime(0,0,0,0,0,0);
						$ActiveEnd = mktime(intval($_POST['deac_hh']), 0, 0, abs(substr($_POST['deac_date'], 5, 2)), abs(substr($_POST['deac_date'], 8, 2)),  substr($_POST['deac_date'], 0, 4));
						if(date("Y-m-d H:i:s",$ActiveEnd) != $shop->CurrentProduct->ActiveEnd)
						{
							$shop->CurrentProduct->setActiveEnd(date("Y-m-d H:i:s",$ActiveEnd));
							$shop->CurrentProduct->setDataChanged(true);
						}
					}
					
					
					/*
					if($shop->CurrentProduct->getDataChanged())
					{ $this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 0 }); '; }
					*/
					/* Attributes */
					
					$i=0;
					if($_POST['att_product'])
					{
						foreach($_POST['att_product'] as $aid)
						{
							if($shop->CurrentProduct->getAttributeValueId($aid) != $_POST['att_val_id'][$i])
							{
								self::setProductAttributeValue($shop->CurrentProduct->getId(), $aid, $_POST['att_predef'][$i], $_POST['att_val_id'][$i], $_POST['att_value'][$i]);
								$shop->CurrentProduct->setDataChanged(true);
								$shop->CurrentProduct->setAttributesLoaded(false);
								$shop->CurrentProduct->setProductAttributesLoaded(false);
								$shop->CurrentProduct->loadAttributes();
							}
							$i++;
						}
					}
					/* Attributes End */
					
					/* Product images */
					if($_FILES)
					{
						$images=0;
						$file_ary = reArrayFiles($_FILES['img_file']);
						if($file_ary)
						{	
							foreach($file_ary as $file)
							{
								if($file["name"] != '')
								{
									if($file['size'] < 2000000)
									{ $images = self::uploadProductImage($file, 0); }
									else
									{ $error['img_file'][$i] = 'image file size exceded 1mb'; }
									$this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 2 }); ';
								}
							}
						}
						$shop->CurrentProduct->setImagesLoaded(false);
					}

					if(intval($_POST['del_img_id']) > 0)
					{ 
						self::deleteProductImage(intval($_POST['del_img_id'])); 
						$this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 2 }); ';
					}
					if(intval($_POST['set_default_img']) > 0)
					{ 
						self::setProductImageDefault($shop->CurrentProduct->getId(), intval($_POST['set_default_img'])); 
						$this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 2 }); ';
					}
					
					$i=0;
					if($_POST['img_id'])
					{
						foreach($_POST['img_id'] as $imageId)
						{
							//self::saveProdImg($shop->CurrentProduct->getId(), $aid, $_POST['img_variation_id'][$i]);
							self::saveProdImg($shop->CurrentProduct->getId(), $imageId, intval($_POST['img_variation_id'][$i]), intval($_POST['img_variation_value_id'][$i]));
							$i++;
						}
					}
					/* Product images End */
					if($shop->CurrentProduct->getDataChanged())
					{ $shop->CurrentProduct->update(); }
					/* Item field actions end */
					
					if((isset($shop->CurrentProduct->Variations)) && (!(intval($_POST['build_variations_all']) > 0)))
					{
						if(($_POST['selected']) && ($_POST['delete_var'] == '-1'))
						{
							foreach($_POST['selected'] as $varid)
							{
								//echo '<br />selected varid:'.$varid;
								if($varid != $shop->CurrentProduct->getFirstVariationId())
								{
									if($shop->CurrentProduct->deleteVariation($varid))
									{ 
										//echo '<br />deleted varid:'.$varid;
										if($this->JsActionRun == '')
										{ $this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 3 }); '; }
									}
								}
								//break;
								//echo '<br />break';
							}
						}
						
						if($_POST['recalculate_prices'] > 0)
						{ $shop->recalculateAllVariationsPrice(); }
										
						/* Variations list actions */
						if(count($_POST['var_id']) > 0)
						{
							$i=0;
							foreach($_POST['var_id'] as $varid)
							{
								if(is_object($shop->CurrentProduct->Variations[$varid]))
								{
									if($_POST['var_id'][$i] == $shop->CurrentProduct->Variations[$varid]->getId())
									{
										$variation = $shop->CurrentProduct->Variations[$varid];
										if($_POST['var_title'][$i] != $variation->getVarTitle())
										{ 
											$variation->setVarTitle($commander->formatText($_POST['var_title'][$i]));
											$variation->setDataChanged(true);
										}
										if($_POST['vActive'][$i] != $variation->getActive())
										{ 
											$variation->setActive($commander->formatText($_POST['vActive'][$i]));
											$variation->setDataChanged(true);
										}
										if($_POST['identity'][$i] != $variation->getIdentity())
										{ 
											$variation->setIdentity($commander->formatText($_POST['identity'][$i]));
											$variation->setDataChanged(true);
										}
										if($_POST['ext_identity'][$i] != $variation->getExtIdentity())
										{ 
											$variation->setExtIdentity($commander->formatText($_POST['ext_identity'][$i]));
											$variation->setDataChanged(true);
										}
										if((intval($_POST['buy_min'][$i]) > 0) && (intval($_POST['buy_min'][$i]) != $variation->getBuyMin()))
										{ 
											$variation->setBuyMin(intval($_POST['buy_min'][$i])); 
											$variation->setDataChanged(true);
										}
										if(!($_POST['recalculate_prices'] > 0))
										{
											if(($_POST['std_price'][$i] > 0) && ($_POST['std_price'][$i] != $variation->getStdPrice()))
											{ 
												$variation->setStdPrice($commander->formatPrice($_POST['std_price'][$i])); 
												$variation->setDataChanged(true);
											}
											if(($_POST['now_price'][$i] != '') && ($_POST['now_price'][$i] != $variation->getNowPrice()))
											{ 
												$variation->setNowPrice($commander->formatPrice($_POST['now_price'][$i])); 
												$variation->setDataChanged(true);
												
												if($_POST['now_price'][$i] == 0)
												{ $variation->setNowPriceDateEnd('0000-00-00 00:00:00'); }
											}
											if(($_POST['NowPriceDateEnd'][$i] != '') && ($_POST['NowPriceDateEnd'][$i] != $variation->getNowPriceDateEnd()))
											{ 
												if($_POST['now_price'][$i] == 0)
												{ $variation->setNowPriceDateEnd('0000-00-00 00:00:00'); }
												else
												{ $variation->setNowPriceDateEnd($_POST['NowPriceDateEnd'][$i]); }
												//echo '$variation->setNowPriceDateEnd('.$_POST['NowPriceDateEnd'][$i].'); ';
												$variation->setDataChanged(true);
											}
											
											if($shop->GlobalSettings['offer_price'])
											{
												if(($_POST['offer_price'][$i]) && ($_POST['offer_price'][$i] != $variation->getOfferPrice()))
												{ 
													$variation->setOfferPrice($commander->formatPrice($_POST['offer_price'][$i])); 
													$variation->setDataChanged(true);
												}
												if(($_POST['offer_start'][$i]) && ($_POST['offer_start'][$i] != $variation->getOfferStart()))
												{ 
													$variation->setOfferStart($_POST['offer_start'][$i]); 
													$variation->setDataChanged(true);
												}
												if(($_POST['offer_end'][$i]) && ($_POST['offer_end'][$i] != $variation->getOfferEnd()))
												{ 
													$variation->setOfferEnd($_POST['offer_end'][$i]); 
													$variation->setDataChanged(true);
												}
											}
										}
										if($shop->GlobalSettings['stock'])
										{
											if((intval($_POST['stock_count'][$i]) > 0) && (intval($_POST['stock_count'][$i]) != $variation->getStockCount()))
											{ 
												$variation->setStockCount(intval($_POST['stock_count'][$i])); 
												$variation->setDataChanged(true);
											}
											//stock_add_date
											if((intval($_POST['stock_add_quan'][$i]) > 0) && (intval($_POST['stock_add_quan'][$i]) != $variation->getStockAddQuan()))
											{ 
												$variation->setStockAddQuan(intval($_POST['stock_add_quan'][$i])); 
												$variation->setDataChanged(true);
											}
											if($_POST['stock_add_txt'][$i] != $variation->getStockAddTxt())
											{ 
												$variation->setStockAddTxt($commander->formatText($_POST['stock_add_txt'][$i]));
												$variation->setDataChanged(true);
											}
										}
										if($shop->GlobalSettings['shipping_weight_volume_active'])
										{
											if(intval($_POST['net_weight'][$i]) != $variation->getNetWeight())
											{ 
												$variation->setNetWeight(intval($_POST['net_weight'][$i])); 
												$variation->setDataChanged(true);
											}
											if(intval($_POST['gros_weight'][$i]) != $variation->getGrosWeight())
											{ 
												$variation->setGrosWeight(intval($_POST['gros_weight'][$i])); 
												$variation->setDataChanged(true);
											}
											if(intval($_POST['length'][$i]) != $variation->getLength())
											{ 
												$variation->setLength(intval($_POST['length'][$i])); 
												$variation->setDataChanged(true);
											}
											if(intval($_POST['width'][$i]) != $variation->getWidth())
											{ 
												$variation->setWidth(intval($_POST['width'][$i])); 
												$variation->setDataChanged(true);
											}
											if(intval($_POST['height'][$i]) != $variation->getHeight())
											{ 
												$variation->setHeight(intval($_POST['height'][$i])); 
												$variation->setDataChanged(true);
											}
										}
										//print_r($variation);
										if($variation->getAttributes())
										{
											foreach($variation->getAttributes() as $att)
											{
												if($att['predefined'] == 1)
												{
													if(intval($_POST['attr_'.$att['id'].'_value_id_'.$varid]) != $att['value']['value_id'])
													{
														$variation->setAttributeValueId($shop->getAttributes(), $att['id'], intval($_POST['attr_'.$att['id'].'_value_id_'.$varid]));
														$variation->setDataChanged(true);
													}
												}
											}
										}
										
										if($variation->getDataChanged())
										{ 
											$variation->update();
											if($this->JsActionRun == '')
											{ $this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 3 }); '; }
										}
										
										if(($_POST['delete_var'] > 0) && ($variation->getId() == $_POST['delete_var']))
										{ 
											if($shop->CurrentProduct->deleteVariation($_POST['delete_var']))
											{ 
												unset($shop->CurrentProduct->Variations[$varid]);
												if($this->JsActionRun == '')
												{ $this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 3 }); '; }
											}
										}
									}
								}
								$i++;
							}
						}
					}
				}
			break;
		}
	}
	
	function buildVariationsOnAtt($buildOnAttId=0, $attValsSet=0, $vals=0)
	{
		//echo '<br />$buildOnAttId:'.$buildOnAttId;
		//echo '<br />MemmoryUsage:'.memory_get_usage();
		unset($av);
		unset($values);
		if(is_array($vals))
		{ $values = $vals; }
		global $shop;
		global $commander;
		set_time_limit(360);
		foreach($shop->CurrentProduct->getAttributes() as $att)
		{
			if($shop->getProductAttribute($att['id']))
			{
				if($att['effect'] == 0)
				{
					if($shop->getProductAttribute($att['id'])->getValue($shop->CurrentProduct->getAttributeValueId($att['id'])))
					{
						$av[$att['id']]['id'] = $att['id'];
						$av[$att['id']]['effect'] = $att['effect'];
						$av[$att['id']]['val'] = $shop->getProductAttribute($att['id'])->getValue($shop->CurrentProduct->getAttributeValueId($att['id']));
					}
				}
				if($att['effect'] == 1)
				{
					unset($avobject);
					if(is_array($attValsSet))
					{ $avobject = $shop->getProductAttribute($att['id'])->getValue(intval($attValsSet[$att['id']])); }
					else
					{ $avobject = $shop->getProductAttribute($att['id'])->getValue(intval($_POST['new_var_attr_'.$att['id'].'_value_id'])); }
					
					if(($att['id'] == intval($buildOnAttId)) && (!isset($values)))
					{ 
						$values = $shop->getProductAttribute($att['id'])->getValues();
						//echo '$values:';
						//print_r($values);
					}
					
					if(is_object($avobject))
					{
						if($avobject->getActive())
						{
							//echo '$avobject:';
							//print_r($avobject);
							
							$av[$att['id']]['id'] = $att['id'];
							$av[$att['id']]['effect'] = $att['effect'];
							
							if(is_array($attValsSet))
							{ $av[$att['id']]['val'] = $avobject; }
							else
							{ $av[$att['id']]['val'] = $avobject; }
							
							//echo '<br />$att[id]:'.$att['id'];
						}
					}
				}
			}
			unset($avobject);
		}
		
		if(isset($av))
		{
			if(isset($values))
			{
				//echo '$values:';
				//print_r($values);
						
				$j=1;
				foreach($values as $value)
				{
					if($value->getActive())
					{
						unset($av[$value->getAttributeId()]);
						
						$av[$value->getAttributeId()]['id'] = $value->getAttributeId();
						$av[$value->getAttributeId()]['val'] = $value;
						$av[$value->getAttributeId()]['effect'] = 1;
						
						$vtitle = '';
						$vident = '';
						$vidLen = 0;
						//Define Variation identity max length
						foreach($av as $v)
						{ $vidLen = $vidLen +strlen($v['val']->getPostfix()); }
						if($vidLen > 0)
						{
							for($k=0; $k < $vidLen; $k++)
							{ $vident .= '*'; }
						}
						
						foreach($av as $v)
						{ 
							if($v['effect'] == 1) //Build variation title on variation attributes only.
							{
								if((trim($v['val']->getValue()) != '') && 
								   (strtolower($v['val']->getValue()) != 'false') && 
								   (strtolower($v['val']->getValue()) != 'ingen') && 
								   (strtolower($v['val']->getValue()) != 'none') && 
								   (strtolower($v['val']->getValue()) != 'nei'))
								{
									if($vtitle != '')
									{ $vtitle .= ' - '.$v['val']->getValue(); }
									else
									{ $vtitle .= $v['val']->getValue(); }
								}
							}
							if($vident != '')
							{ 
								if($v['val']->getPostfixPosition() == 0)
								{ $vident = $v['val']->getPostfix().$vident; }
								else
								{
									if($v['val']->getPostfixPosition() > strlen($vident))
									{ $vident = $v['val']->getPostfix().$vident; }
									else
									{ 
										$firstPart = '';
										$lastPart  = '';
										$firstPart = substr($vident,0,$v['val']->getPostfixPosition());
										$lastPart  = substr($vident,$v['val']->getPostfixPosition(),strlen($vident));
										$vident = $firstPart.$v['val']->getPostfix().$lastPart;
									}
								}
							}
							else
							{ $vident .= $v['val']->getPostfix(); }
						}
						if($vtitle == '')
						{ $vtitle = ucfirst($txt->getWord('new').' '.$txt->getWord('variation')); }
						
						$vident = str_replace('*','',$vident);
						//echo 'firstvar - valueId:'.$shop->CurrentProduct->getVariation(1)->getAttributeValueId($value->getAttributeId());
						
						//Check if variation with current combination exists
						$exists = 0;
						//if(isset($attValsSet)) //When running this combination does not exist and is allready checked
						//{ $exists = 0; }
						//else
						//{
							foreach($shop->CurrentProduct->getVariations() as $variation)
							{
								$found = 0;
								foreach($av as $v)
								{
									if($v['effect'] == 1)
									{ 
										if($variation->getAttributeValueId($v['id']) == $v['val']->getId())
										{ $found++; }
									}
									else
									{ 
										if($shop->CurrentProduct->getAttributeValueId($v['id']) == $v['val']->getId())
										{ $found++; }
									}
									
								}
								if($found == count($av))
								{ 
									$exists = 1;
									break; 
								}
							}
						//}
						//echo '<br />';
						if($exists == 0)
						{
							//echo '<br />goOnValueId:'.$value->getId();
							$shop->CurrentProduct->setFirstVariationLoaded(false);
							$shop->CurrentProduct->setVariationsLoaded(false);
							//#Preradi
							if(isset($attValsSet))
							{ $newVarNum = $shop->CurrentProduct->addVariation($commander->formatText($vtitle), $vident, 0); }
							else
							{ $newVarNum = $shop->CurrentProduct->addVariation($commander->formatText($vtitle), $vident, 1); }
							//echo '<br />$newVarNum:'.$newVarNum;
							//print_r($shop->CurrentProduct->getVariation($newVarNum));
							if($shop->CurrentProduct->getVariation($newVarNum))
							{
								foreach($av as $v)
								{
									$shop->CurrentProduct->getVariation($newVarNum)->setAttributeValueId($shop->getAttributes(), $v['val']->getAttributeId(), $v['val']->getId());
									$shop->CurrentProduct->getVariation($newVarNum)->setDataChanged(true);
								}
							}
						}
					}
				}
			}
		}
		unset($av);
		unset($values);
		return;
	}
	
	function buildAllVariations($buildOn=0)
	{
		//echo 'buildAllVariations<br />';
		//echo '<br />MemmoryUsage:'.memory_get_usage();
		set_time_limit(360);
		global $shop;
		if($shop->CurrentProduct->getAttributesVar())
		{	
			$buildOn = 0;
			
			//buildVariationsOnAtt($buildOnAttId=0, $attValsSet=0)
			$i = 0;
			$j = 0;
			$k = 0;
			$l = 0;
			
			$totAttCount = count($shop->CurrentProduct->getAttributesVar());
			$prodAttVals = 0;
			$attributes = array_reverse($shop->CurrentProduct->getAttributesVar());
			
			foreach($attributes  as $attribute)
			{
				if($attribute['effect'] == 1)
				{
					if($buildOn == 0)
					{ $buildOn = $attribute['id']; } //Allways build on last attribute
				}
				else
				{ $prodAttVals++; }
			}
			
			//echo '<br />Build on variationID:'.$buildOn;
			
			if($buildOn > 0) // Must have something to build on
			{
				for($i=0; $i<$totAttCount; $i++)
				{
					//echo '<br />$i:'.$i;
					$j=0;
					
					foreach($attributes  as $attribute) //Get First Value Only
					{
						if(($attribute['effect'] == 1) && ($attribute['id'] != $buildOn) && ($j != $i))
						{
							$attValues = $shop->getProductAttribute($attribute['id'])->getValues();
							$attValsSetStatic[$i][$attribute['id']] = 0;
							
							foreach($attValues as $attValue)
							{
								if(($attValue->getActive() > 0) && (!($attValsSetStatic[$i][$attribute['id']] > 0)))
								{ $attValsSetStatic[$i][$attribute['id']] = $attValue->getId(); }
							}
						}
						$j++;
					}
					
					//echo '<br />count($attValsSetStatic['.$i.']):'.count($attValsSetStatic[$i]);
					
					if(count($attValsSetStatic[$i]) == ($totAttCount-2))
					{
						//echo '<br />count($attValsSet):'.count($attValsSetStatic[$i]);
						//echo '<br />$attValsSetStatic['.$i.']:';
						//print_r($attValsSetStatic[$i]);
						
						$j=0;
						foreach($attributes  as $attribute)
						{
							//echo '<br />$j:'.$j;
							if(($attribute['effect'] == 1) && ($attribute['id'] != $buildOn) && ($j == $i))
							{
								//echo '<br />LoopValuesOnAttribute:'.$attribute['id'];
								
								$attValues = $shop->getProductAttribute($attribute['id'])->getValues();
								$l=0;
								foreach($attValues as $attValue)
								{
									$k=0;
									$attValsSet[$i][$l][$k] = $attValsSetStatic[$i];
									if($attValue->getActive() > 0)
									{ 
										$attValsSet[$i][$l][$k][$attribute['id']] = $attValue->getId(); 
										
										if(count($attValsSet[$i][$l][$k]) == ($totAttCount-1))
										{
											//echo '<br />count($attValsSet['.$i.']['.$l.']['.$k.']):'.count($attValsSet[$i][$l][$k]);
											//echo '<br />$attValsSet['.$i.']['.$l.']['.$k.']&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:';
											//ksort($attValsSet[$i][$l][$k]);
											//print_r($attValsSet[$i][$l][$k]);
						
											if($i > 1)
											{
												//echo '<br />Subsets:';
												for($m=1; $m<$i; $m++) //$m = $i
												{
													//echo '<br />$k:'.$k;
													if(isset($attValsSet[$m]))
													{
														foreach(array_keys($attValsSet[$m]) as $n) //$n = $j
														{
															if(isset($attValsSet[$m][$n]))
															{
																foreach(array_keys($attValsSet[$m][$n]) as $key) //$n = $j
																{
																	$k++;
																	
																	$attValsSubSet[$m][$n][$k] = $attValsSet[$m][$n][$key];
																	$attValsSubSet[$m][$n][$k][$attribute['id']] = $attValue->getId(); 
																	
																	//echo '<br />$attValsSet['.$m.']['.$n.']['.$k.']:';
																	ksort($attValsSubSet[$m][$n][$k]);
																	
																	
																	//print_r($attValsSubSet[$m][$n][$k]);
																	
																	$attValsSet[$i][$l][$k] = $attValsSubSet[$m][$n][$k];
																	ksort($attValsSet[$i][$l][$k]);
																	unset($attValsSubSet[$m][$n][$k]);
																	//Furaj na subset k-1
																}
															}
														}
													}
												}
												//echo '<br />Subsets END';
											}
											if($i == ($totAttCount-1))
											{
												$fullSet = $attValsSet[$i][$l];
												unset($attValsSet);
												
												foreach(array_keys($fullSet) as $key)
												{
													foreach(array_keys($fullSet) as $chk)
													{
														if(($fullSet[$key] == $fullSet[$chk]) && ($key != $chk))
														{ unset($fullSet[$key]); }
													}
												}
												
												$x = 0;
												foreach(array_keys($fullSet) as $key)
												{
													$finalSet[$x] = $fullSet[$key];
													$x++;
												}
												unset($fullSet);
											}
										}
										$l++;
									}
								}
							}
							$j++;
						}
					}
					//echo '<br />';
				}
				unset($attributes);
				if(isset($finalSet))
				{ 
					$vals = $shop->getProductAttribute($buildOn)->getValues();
					
					self::buildVariationsOnArray($buildOn, $finalSet, $vals); 
					unset($finalSet);
					return;
				}
			}
		}
	}
	
	function buildVariationsOnArray($buildOn=0, $finalSet, $vals, $lastIndex=0, $chunk=100, $totCount=0, $round=0)
	{
		set_time_limit(3600);
		//echo '<br />buildVariationsOnArray<br />MemmoryUsage:'.memory_get_usage();
		if(($buildOn > 0) && (is_array($finalSet)))
		{
			$round++;
			
			if($totCount == 0)
			{ $totCount = count($finalSet); }
			
			$i = 0;
			foreach(array_keys($finalSet) as $key)
			{
				if($i < $chunk)
				{
					if(($key > $lastIndex) || ($lastIndex == 0))
					{
						echo '<br />Combination:['.$key.']:';
						print_r($finalSet[$key]);
						self::buildVariationsOnAtt($buildOn, $finalSet[$key], $vals);
						unset($finalSet[$key]);
						$lastIndex = $key;
					}
				}
				else
				{ break; }
				$i++;
			}
			if((count($finalSet) > 0) && (($chunk*$round) < $totCount))
			{
				/*
				DELETE FROM `hc_product_vars` WHERE `product_id` =16 AND `id` > 25;
				
				DELETE FROM `hc_product_var_vals` WHERE `product_id` =16 AND `variation_id` > 25;
				
				echo '<br />Next Round values:';
				echo '<br />count($finalSet):'.count($finalSet);
				echo '<br />$lastIndex:'.$lastIndex;
				echo '<br />$totCount:'.$totCount;
				echo '<br />$round:'.$round;
				*/
				self::buildVariationsOnArray($buildOn, $finalSet, $vals, $lastIndex, $chunk, $totCount, $round);
			}
			else
			{
				unset($finalSet);
				return;
			}
		}
	}
	
	function addProduct($title, $parent, $identity='', $groupId=0, $catId=0, $tax=0)
	{
		global $commander;
		global $shop;
		if(($title != '') && (is_numeric($parent)))
		{
			if(!(intval($groupId) > 0))
			{ $groupId = 0; }
			if(!(intval($catId) > 0))
			{ $catId = 0; }
			
			$neworder = 0;
			$result = mysql_query('UPDATE `'.DB_PERFIX.'product` SET `product_order` = product_order+1 WHERE `section_id`='.$parent.';');
			
			$title = $commander->formatText($title);
			$alias = $commander->formatAlias($title);
			
			if(strlen($title) > 60)
			{ $title = substr($title, 0, 60); }
			
			$insert = '`section_id`';
			$values = ''.$parent.'';
			
			$insert .= ', `title`';
			$values .= ', "'.$title.'"';
			
			$insert .= ', `alias`';
			$values .= ', "'.$alias.'"';
			
			$insert .= ', `product_order`';
			$values .= ', '.$neworder.'';
				
			$insert .= ', `stock_unit`';
			$values .= ', "'.$shop->GlobalSettings['stock_unit'].'"';
			
			$insert .= ', `weight_unit`';
			$values .= ', "'.$shop->GlobalSettings['weight_unit'].'"';
			
			$insert .= ', `dim_unit`';
			$values .= ', "'.$shop->GlobalSettings['dim_unit'].'"';
			
			if(intval($groupId) > 0)
			{
				$insert .= ', `group_id`';
				$values .= ', '.intval($groupId).'';
			}
			if(intval($catId) > 0)
			{
				$insert .= ', `cat_id`';
				$values .= ', '.intval($catId).'';
			}
			if((intval($tax) > 0) && (intval($tax) != $shop->getGlobalSetting('default_tax_id')))
			{
				$insert .= ', `tax_id`';
				$values .= ', '.intval($tax).'';
			}
			else
			{
				$insert .= ', `tax_id`';
				$values .= ', '.$shop->getGlobalSetting('default_tax_id').'';
			}
			
			$insert .= ', `date_created`';
			$values .= ', NOW()';
			
			$sql  = 'INSERT INTO '.DB_PERFIX.'product ('.$insert.') '; 
			$sql .= 'VALUES ('.$values.');';
			$result = mysql_query($sql);
			
			echo $sql;
			//INSERT INTO hc_product (`section_id`, `title`, `alias`, `product_order`, `date_created`, `stock_unit`, `weight_unit`, `dim_unit`, `tax_id`)VALUES (7, "Annonse - Med Gallerivisning", "annonse_-_med_gallerivisning", 0, NOW(), "", "", "", );
			
			$result = mysql_query('SELECT id FROM '.DB_PERFIX.'product WHERE title LIKE "'.$title.'" AND section_id='.$parent.' ORDER BY id DESC LIMIT 1;');
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{
					$item['id'] = $row['id'];
					$item['title'] = $name;
				}
			}
			
			if($identity == '')
			{ $identity = $parent.'-'.$item['id'].'-0'; }
			
			$insert  = 'INSERT INTO '.DB_PERFIX.'product_vars (`product_id`, `identity`, `var_title`)'; 
			$insert .= 'VALUES ('.$item['id'].', "'.$identity.'", "Standard");';
			$result = mysql_query($insert);
			//echo $insert;
			$item = self::getProduct($item['id']);
			//return $item;
			/*
			if($parent > 0)
			{ $result = mysql_query('UPDATE '.DB_PERFIX.'menu SET has_products=1 WHERE id='.$parent.';'); }
			*/
		}
	}
	
	function addProductAttribute($title)
	{
		global $commander;
		$title = $commander->formatText($title);
		if($title != '')
		{
			$insert  = 'INSERT INTO '.DB_PERFIX.'product_attributes (`title`)'; 
			$insert .= 'VALUES ("'.$title.'");';
			$result = mysql_query($insert);
			return;
		}
	}
	
	function addProductAttributeValue($value)
	{
		global $commander;
		$value = $commander->formatText($value);
		if(($value != '') && (self::getCurrentAttributeId() > 0))
		{
			$neworder = 0;
			$result = mysql_query('SELECT value_order FROM '.DB_PERFIX.'product_attribute_values WHERE attribute_id='.self::getCurrentAttributeId().' ORDER BY value_order DESC LIMIT 1;');
			while($row = mysql_fetch_array($result))
			{ $neworder = $row['value_order']; }
			$neworder++;
			
			$insert  = 'INSERT INTO '.DB_PERFIX.'product_attribute_values (`attribute_id`, `value`, `value_order`)'; 
			$insert .= 'VALUES ('.self::getCurrentAttributeId().', "'.$value.'", '.$neworder.');';
			$result = mysql_query($insert);
			return;
		}
	}
	
	function deleteProductAttribute($id)
	{	
		if($id > 0)
		{	
			$sql = 'DELETE FROM '.DB_PERFIX.'product_attribute_values WHERE attribute_id='.$id.';';
			$result = mysql_query($sql);
			
			$sql = 'DELETE FROM '.DB_PERFIX.'product_attributes WHERE id='.$id.' LIMIT 1;';
			$result = mysql_query($sql);
			
			return ;
		}
	}
	
	function deleteProductAttributeValue($id, $del_existing=1)
	{
		if($id > 0)
		{
			$sql = 'DELETE FROM '.DB_PERFIX.'product_vals WHERE value_id='.$id.';';
			$result = mysql_query($sql);
			$sql = 'DELETE FROM '.DB_PERFIX.'product_var_vals WHERE value_id='.$id.';';
			$result = mysql_query($sql);
			$sql = 'DELETE FROM '.DB_PERFIX.'product_attribute_values WHERE id='.$id.' LIMIT 1;';
			$result = mysql_query($sql);
			return ;
		}
	}
	
	function loadProduct()
	{
		if($this->CurrentProductId > 0)
		{
			$sql  = 'SELECT * FROM '.DB_PERFIX.'product AS product  ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'product_vars AS product_vars ON product.id=product_vars.product_id ';
			$sql .= 'WHERE product.id='.$this->CurrentProductId.' LIMIT 1;';
			
			$result = mysql_query($sql);
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{ $item = $row; }
				if($item['id'] > 0)
				{
					$item['attributes'] = self::getProductAttributes($item['id']);
					$item['vals'] = self::getProductAttrValues($item['id']);
					$item['images'] = self::getProductImages($item['id']);
					return $item;
				}
			}
		}
	}
	
	function getProduct($id=0, $identity='')
	{
		if(($id > 0) || ($identity != ''))
		{
			$queery  = 'SELECT * FROM '.DB_PERFIX.'product AS product  ';
			$queery .= 'LEFT JOIN '.DB_PERFIX.'product_vars AS product_vars ON product.id=product_vars.product_id ';
			if((!($id > 0)) && ($identity != ''))
			{ $queery .= 'WHERE product_vars.identity="'.$identity.'" LIMIT 1;'; }
			else
			{ $queery .= 'WHERE product.id='.$id.' LIMIT 1;'; }
			
			$result = mysql_query($queery);
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{ $item = $row; }
				if($item['id'] > 0)
				{
					$item['attributes'] = self::getProductAttributes($item['id']);
					$item['vals'] = self::getProductAttrValues($item['id']);
					$item['images'] = self::getProductImages($item['id']);
					return $item;
				}
			}
		}
	}
	
	function getProductImages($pid, $default=0)
	{
		$seldef = '';
		if($default == 1)
		{ $seldef = ' AND default=1 '; }
		$select = 'SELECT * FROM '.DB_PERFIX.'shop_images WHERE product_id='.$pid.$seldef.';';
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			$i=0;
			while($row = mysql_fetch_array($result))
			{
				foreach(array_keys($row) as $key)
				{ $item[$i][$key] = $row[$key]; }
				$item[$i]['URL'] = PRODUCT_URL.$item[$i]['image'];
				$i++;
			}
			return $item;
		}
	}
	
	function getProductImage($id)
	{
		if($id > 0)
		{
			$select = 'SELECT * FROM '.DB_PERFIX.'shop_images WHERE id='.$id.' LIMIT 1;';
			$result = mysql_query($select);
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{
					foreach(array_keys($row) as $key)
					{ $item[$key] = $row[$key]; }
					$item['URL'] = PRODUCT_URL.$item[$i]['image'];
				}
				return $item;
			}
		}
	}
	
	function setProductImageDefault($pid, $iid)
	{
		if(($pid > 0) && ($iid > 0))
		{
			$sql = 'UPDATE '.DB_PERFIX.'shop_images SET `default`=0 WHERE product_id='.$pid.';'; 
			$result = mysql_query($sql);
			$sql = 'UPDATE '.DB_PERFIX.'shop_images SET `default`=1 WHERE id='.$iid.' LIMIT 1;';
			$result = mysql_query($sql);
		}
	}
	
	function saveProdImg($productId, $imageId, $variationId=0, $variationValueId=0)
	{
		if(($productId > 0) && ($imageId > 0))
		{
			if($variationValueId > 0)
			{ $variationId=0; }
			
			$sql  = 'UPDATE '.DB_PERFIX.'shop_images SET ';
			$sql .= 'variation_id='.intval($variationId).', ';
			$sql .= 'variation_value_id='.intval($variationValueId).' ';
			$sql .= 'WHERE id='.$imageId.' AND product_id='.intval($productId).';'; 
			
			$result = mysql_query($sql);
		}
	}
	
	function deleteProductImage($id)
	{
		if($id > 0)
		{
			global $thumb;
			$image = self::getProductImage($id);
			if($image)
			{
				if (is_file(PRODUCT_PATH.$image['image']))
				{ 
					unlink(PRODUCT_PATH.$image['image']); 
					$daName = $image['image'];
					
					if($thumb['PRODUCT'])
					{
						foreach($thumb['PRODUCT'] as $tmb)
						{
							if($i == 0)
							{ 
								$new_name = $daName; 
								$i = 1;
							}
							else
							{ $new_name = $tmb['MAXW'].'_'.$daName; }
							
							if(is_file(PRODUCT_PATH.$daName))
							{ unlink(PRODUCT_PATH.$daName); }
						}
					}
					$delete = 'DELETE FROM '.DB_PERFIX.'shop_images WHERE id='.$id.' LIMIT 1;';
					$result = mysql_query($delete);
					return ;
				}
			}
		}
	}
	
	function getProductAttributes($pid=0)
	{
		if($pid > 0)
		{
			$select = ' SELECT attr.* FROM '.DB_PERFIX.'product_attributes AS attr ';
			$select = $select.' LEFT JOIN '.DB_PERFIX.'product_to_attributes AS pta ON pta.attribute_id=attr.id ';
			$select = $select.' WHERE pta.product_id='.$pid.' ORDER BY pta.id ASC;';
			$result = mysql_query($select);
			if(mysql_num_rows($result) > 0)
			{
				$i=0;
				while($row = mysql_fetch_array($result))
				{
					foreach(array_keys($row) as $key)
					{ $item[$i][$key] = $row[$key]; }
					
					$item[$i]['value'] = self::getProductAttrValue($pid, $row['id']);
					$i++;
				}
				return $item;
			}
		}
	}
	
	function getProductAttrValue($pid=0, $aid=0)
	{
		if(($pid > 0) && ($aid > 0))
		{
			$select = ' SELECT * FROM '.DB_PERFIX.'product_vals WHERE product_id='.$pid.' AND attribute_id='.$aid.' LIMIT 1;';
			$result = mysql_query($select);
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{
					$item['id'] = $row['id'];
					$item['product_id'] = $row['product_id'];
					$item['attribute_id'] = $row['attribute_id'];
					$item['value_id'] = $row['value_id'];
					$item['value'] = $row['value'];
				}
				
			}
			return $item;
		}
	}
	
	function getProductAttrValues($pid=0)
	{
		if($pid > 0)
		{
			$select = ' SELECT * FROM '.DB_PERFIX.'product_vals WHERE product_id='.$pid.' ORDER BY attribute_id ASC;';
			$result = mysql_query($select);
			if(mysql_num_rows($result) > 0)
			{
				$i=0;
				while($row = mysql_fetch_array($result))
				{
					foreach(array_keys($row) as $key)
					{ $item[$i][$key] = $row[$key]; }
					$i++;
				}
				return $item;
			}
		}
	}
	
	function setProductAttributeValue($productId, $attId, $predef, $valueid=0, $value='')
	{
		if(($productId > 0) && ($attId > 0) && (($valueid > 0) || ($value != '')))
		{
			$found = 0;
			$select = 'SELECT * FROM '.DB_PERFIX.'product_vals WHERE product_id='.$productId.' AND attribute_id='.$attId.';';
			$result = mysql_query($select);
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{ $found = $row['id']; }
			}
			
			if(($predef > 0) && ($valueid > 0))
			{
				$select = 'SELECT value FROM '.DB_PERFIX.'product_attribute_values WHERE id='.$valueid.' AND attribute_id='.$attId.';';
				$result = mysql_query($select);
				if(mysql_num_rows($result) > 0)
				{
					while($row = mysql_fetch_array($result))
					{ $value = $row['value']; }
				}
			}
			else
			{ $valueid=0; }
			
			if($found > 0)
			{ $sql = 'UPDATE '.DB_PERFIX.'product_vals SET value_id='.$valueid.', value="'.$value.'" WHERE id='.$found.' AND attribute_id='.$attId.';'; }
			else
			{ $sql  = 'INSERT INTO '.DB_PERFIX.'product_vals (`product_id`, `attribute_id`, `value_id`, `value`) VALUES ('.$productId.', '.$attId.', '.$valueid.', "'.$value.'");'; }
			//echo $sql;
			$result = mysql_query($sql);
		}
	}
	
	function getProductVars($productid, $varnum=0, $identity='', $minvarnum=0)
	{
		if($productid > 0)
		{
			$queery  = 'SELECT * FROM '.DB_PERFIX.'product_vars WHERE product_id='.$productid.';';
			
			$result = mysql_query($queery);
			if(mysql_num_rows($result) > 0)
			{
				$i = 0;
				while($row = mysql_fetch_array($result))
				{
					foreach(array_keys($row) as $key)
					{ $item[$i][$key] = $row[$key]; }
					$i++;
				}
				return $item;
			}
		}
	}

	function deleteProduct($id)
	{
		if($id > 0)
		{
			global $shop;
			if(isset($shop->ProductList[$id]))
			{
				$images = $shop->ProductList[$id]->getImages();
				if($images)
				{ self::deleteProductImages($images); }
				$delete = 'DELETE FROM '.DB_PERFIX.'shop_cart_items WHERE product_id='.$id.';';
				$result = mysql_query($delete);
				$delete = 'DELETE FROM '.DB_PERFIX.'product_to_attributes WHERE product_id='.$id.';';
				$result = mysql_query($delete);
				$delete = 'DELETE FROM '.DB_PERFIX.'product_to_cats WHERE product_id='.$id.';';
				$result = mysql_query($delete);
				$delete = 'DELETE FROM '.DB_PERFIX.'product_to_menu WHERE product_id='.$id.';';
				$result = mysql_query($delete);
				$delete = 'DELETE FROM '.DB_PERFIX.'product_vals WHERE product_id='.$id.';';
				$result = mysql_query($delete);
				$delete = 'DELETE FROM '.DB_PERFIX.'product_var_vals WHERE product_id='.$id.';';
				$result = mysql_query($delete);
				$delete = 'DELETE FROM '.DB_PERFIX.'product_vars  WHERE product_id='.$id.';'; 
				$result = mysql_query($delete);
				$delete = 'DELETE FROM '.DB_PERFIX.'product WHERE id='.$id.' LIMIT 1;';
				$result = mysql_query($delete);
				return true;
			}
		}
	}
	
	function deleteProductImages($images)
	{
		global $thumb;
		if($images)
		{
			foreach($images as $image)
			{
				if($image)
				{
					if (is_file(PRODUCT_PATH.$image['image']))
					{ 
						unlink(PRODUCT_PATH.$image['image']); 
						$daName = $image['image'];
						
						if($thumb['PRODUCT'])
						{
							foreach($thumb['PRODUCT'] as $tmb)
							{
								if($i == 0)
								{ 
									$new_name = $daName; 
									$i = 1;
								}
								else
								{ $new_name = $tmb['MAXW'].'_'.$daName; }
								if(is_file(PRODUCT_THUMB_PATH.$new_name))
								{ unlink(PRODUCT_THUMB_PATH.$new_name); }
							}
						}
						$delete = 'DELETE FROM '.DB_PERFIX.'shop_images WHERE id='.$image['id'].' LIMIT 1;';
						$result = mysql_query($delete);
						return ;
					}
				}
			}
		}
	}
	
	function addAttributeToProduct($product, $attribute)
	{
		if(($product > 0) && ($attribute > 0))
		{ 
			global $db;
			$error['add_attribute'] = $db->addTablesCombination('product_id', $product, 'attribute_id', $attribute, 'product_to_attributes'); 
		}
	}
	
	function remAttributeFromProduct($product, $attribute)
	{
		if(($product > 0) && ($attribute > 0))
		{
			global $db;
			
			$delete = 'DELETE FROM '.DB_PERFIX.'product_vals WHERE product_id='.$product.' AND attribute_id='.$attribute.' LIMIT 1;';
			$result = mysql_query($delete);
			
			$delete = 'DELETE FROM '.DB_PERFIX.'product_var_vals WHERE product_id='.$product.' AND attribute_id='.$attribute.' LIMIT 1;';
			$result = mysql_query($delete);
			
			$error['rem_attribute'] = $db->remTablesCombination('product_id', $product, 'attribute_id', $attribute, 'product_to_attributes');
		}
	}
	
	function getProductGroups()
	{
		$i=0;
		$result = mysql_query('SELECT * FROM '.DB_PERFIX.'product_groups;');
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				$item[$i]['id'] = $row['id'];
				$item[$i]['title'] = $row['title'];
				$item[$i]['title_import'] = $row['title_import'];
				$item[$i]['active'] = $row['active'];
				$i++;
			}
			return $item;
		}
	}

	function addShopProvider($title, $titleImport='', $country='', $city='')
	{
		global $commander;
		$title = $commander->formatText($title);
		if($titleImport != '')
		{ $titleImport = $commander->formatAlias($titleImport); }
		else
		{ $titleImport = $commander->formatAlias($title); }
		
		$country = $commander->formatText($country);
		$city = $commander->formatText($city);
		
		if($title != '')
		{
			$insert  = 'INSERT INTO '.DB_PERFIX.'product_providers (`title`, `title_import`, `country`, `city`)'; 
			$insert .= 'VALUES ("'.$title.'", "'.$titleImport.'", "'.$country.'", "'.$city.'");';
			$result = mysql_query($insert);
		}
	}
	
	function deleteShopProvider($id)
	{	
		if($id > 0)
		{	
			$sql = 'DELETE FROM '.DB_PERFIX.'product_provider_to_brands WHERE provider_id='.intval($id).';';
			$result = mysql_query($sql);
			$sql = 'UPDATE '.DB_PERFIX.'product SET provider=0 WHERE provider='.intval($id).';';
			$result = mysql_query($sql);
			$sql = 'DELETE FROM '.DB_PERFIX.'product_providers WHERE id='.intval($id).' LIMIT 1;';
			$result = mysql_query($sql);
			return;
		}
	}
	
	function addShopBrand($title, $titleImport='', $country='')
	{
		global $commander;
		$title = $commander->formatText($title);
		if($titleImport != '')
		{ $titleImport = $commander->formatAlias($titleImport); }
		else
		{ $titleImport = $commander->formatAlias($title); }
		$country = $commander->formatText($country);
		if($title != '')
		{
			$insert  = 'INSERT INTO '.DB_PERFIX.'product_brands (`title`, `title_import`, `country`)'; 
			$insert .= 'VALUES ("'.$title.'", "'.$titleImport.'", "'.$country.'");';
			$result = mysql_query($insert);
		}
	}
	
	function deleteShopBrand($id)
	{	
		if($id > 0)
		{	
			$sql = 'DELETE FROM '.DB_PERFIX.'product_provider_to_brands WHERE brand_id='.intval($id).';';
			$result = mysql_query($sql);
			$sql = 'UPDATE '.DB_PERFIX.'product SET brand=0 WHERE brand='.intval($id).';';
			$result = mysql_query($sql);
			$sql = 'DELETE FROM '.DB_PERFIX.'product_brands WHERE id='.intval($id).' LIMIT 1;';
			$result = mysql_query($sql);
			return;
		}
	}
	
	function addProductCat($title, $titleImport='')
	{
		global $commander;
		$title = $commander->formatText($title);
		if($titleImport != '')
		{ $titleImport = $commander->formatAlias($titleImport); }
		else
		{ $titleImport = $commander->formatAlias($title); }
		if($title != '')
		{
			$insert  = 'INSERT INTO '.DB_PERFIX.'product_cats (`title`, `title_import`)'; 
			$insert .= 'VALUES ("'.$title.'", "'.$titleImport.'");';
			$result = mysql_query($insert);
			if ($result > 0)
			{
				$result = mysql_query("SELECT * FROM ".DB_PERFIX."product_cats WHERE title LIKE '".$title."' ORDER BY id DESC LIMIT 1;");
				while($row = mysql_fetch_array($result))
				{
					$item['id'] = $row['id'];
					$item['title'] = $row['title'];
					$item['title_import'] = $row['title_import'];
					$item['active'] = $row['active'];
				}
			}
			return $item;
		}
	}
	
	function deleteProductCat($id)
	{	
		if($id > 0)
		{
			$sql = 'UPDATE '.DB_PERFIX.'product SET cat_id=0 WHERE cat_id='.$id.';';
			$result = mysql_query($sql);
			
			$delete = 'DELETE FROM '.DB_PERFIX.'product_cats WHERE id='.$id.' LIMIT 1;';
			$result = mysql_query($delete);
			return ;
		}
	}
	
	function addProductGroup($title, $titleImport='')
	{
		global $commander;
		$title = $commander->formatText($title);
		if($titleImport != '')
		{ $titleImport = $commander->formatAlias($titleImport); }
		else
		{ $titleImport = $commander->formatAlias($title); }
		if($title != '')
		{
			$insert  = 'INSERT INTO '.DB_PERFIX.'product_groups (`title`, `title_import`)'; 
			$insert .= 'VALUES ("'.$title.'", "'.$titleImport.'");';
			$result = mysql_query($insert);
			if ($result > 0)
			{
				$result = mysql_query("SELECT * FROM ".DB_PERFIX."product_groups WHERE title LIKE '".$title."' ORDER BY id DESC LIMIT 1;");
				while($row = mysql_fetch_array($result))
				{
					$item['id'] = $row['id'];
					$item['title'] = $row['title'];
					$item['title_import'] = $row['title_import'];
					$item['active'] = $row['active'];
				}
			}
			return $item;
		}
	}
	
	function deleteProductGroup($id)
	{	
		if($id > 0)
		{
			$sql = 'UPDATE '.DB_PERFIX.'product SET group_id=0 WHERE group_id='.$id.';';
			$result = mysql_query($sql);
			
			$delete = 'DELETE FROM '.DB_PERFIX.'product_groups WHERE id='.$id.' LIMIT 1;';
			$result = mysql_query($delete);
			return ;
		}
	}
	
	function getProductBrands()
	{
		$i=0;
		$result = mysql_query("SELECT * FROM ".DB_PERFIX."product_brands;");
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				foreach(array_keys($row) as $key)
				{ $item[$row['id']][$key] = $row[$key]; }
			}
			return $item;
		}
	}
	
	function getProductBrand($id)
	{
		if($id > 0)
		{
			$result = mysql_query('SELECT * FROM '.DB_PERFIX.'product_brands WHERE id='.$id.';');
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{
					foreach(array_keys($row) as $key)
					{ $item[$key] = $row[$key]; }
				}
				return $item;
			}
		}
	}
	
	function getProducts($sec=0, $cat=0)
	{
		$i=0;
		if($sec > 0)
		{ $where = ' AND section_id='.$sec; }
		if($cat > 0)
		{ $where = ' AND cat_id='.$cat; }
		
		$select = 'SELECT * FROM '.DB_PERFIX.'product WHERE id > 0 '.$where.';'; 
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			$i = 0;
			while($row = mysql_fetch_array($result))
			{
				foreach(array_keys($row) as $key)
				{ $item[$i][$key] = $row[$key]; }
				$i++;
			}
			return $item;
		}
		return $item;
	}
	
	function getProductsCount($sec=0, $cat=0)
	{
		$count=0;
		if($sec > 0)
		{ $where = ' AND section_id='.$sec; }
		if($cat > 0)
		{ $where = ' AND cat_id='.$cat; }
		
		$select = 'SELECT COUNT(*) as total FROM '.DB_PERFIX.'product WHERE id > 0 '.$where.';'; 
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{ $count = $row['total']; }
		}
		return $count;
	}

	function moveProductFromCatToCat($id, $from_catid, $to_catid)
	{
		if(($id > 0) && ($from_catid > 0) && ($to_catid > 0))
		{
			$sql = 'UPDATE '.DB_PERFIX.'product_to_cats SET cat_id='.$to_catid.' WHERE product_id='.$id.' AND cat_id='.$from_catid.';';
			$result = mysql_query($sql);
			return $result; 
		}
	}
	
	function moveProductCat($id, $to_catid)
	{
		if(($id > 0) && ($to_catid > 0))
		{
			$sql = 'UPDATE '.DB_PERFIX.'product_cats SET parent_id='.$to_catid.' WHERE id='.$id.';';
			$result = mysql_query($sql);
			return $result; 
		}
	}
	
	function getProductBrandsMenuHTML()
	{
		global $shop;
		$items = $shop->getBrands();
		if($items)
		{
			$output .= '<ul>';
			foreach($items as $item)
			{
				$style = ' style="background-image:url('.SYSICONS_URL.'treemenu/brands_16.png)" ';
				$output .= '<li id="brand_'.$item->getId().'" class="'.$li_class.' leaf" '.$state.' rel="product_brand">';
				$output .= '<a '.$style.' href="?con='.intval($_REQUEST['con']).'&amp;brand='.$item->getId().'">';
				$output .= $item->getTitle();
				$output .= '</a>';
				$output .= '</li>';	
			}
			$output .= '</ul>';
		}
		return $output;
	}
	
	function getShopProvidersMenuHTML()
	{
		global $shop;
		$items = $shop->getProviders();
		if($items)
		{
			$output .= '<ul>';
			foreach($items as $item)
			{
				$style = ' style="background-image:url(img/list_users.gif)" ';
				$output .= '<li id="provider_'.$item->getId().'" class="'.$li_class.' leaf" '.$state.' rel="product_cat">';
				$output .= '<a '.$style.' href="?con='.intval($_REQUEST['con']).'&amp;provider='.$item->getId().'">';
				$output .= $item->getTitle();
				$output .= '</a>';
				$output .= '</li>';
			}
			$output .= '</ul>';
		}
		return $output;
	}
	
	function getProductGroupsMenuHTML()
	{
		global $shop;
		$items = $shop->getGroups();
		if($items)
		{
			$output .= '<ul>';
			foreach($items as $item)
			{
				$style = ' style="background-image:url('.SYSICONS_URL.'treemenu/brands_16.png)" ';
				$output .= '<li id="grp_'.$item->getId().'" class="'.$li_class.' leaf" '.$state.' rel="product_grp">';
				$output .= '<a '.$style.' href="?con='.intval($_REQUEST['con']).'&amp;grp='.$item->getId().'">';
				$output .= $item->getTitle();
				$output .= '</a>';
				$output .= '</li>';	
			}
			$output .= '</ul>';
		}
		return $output;
	}
	
	function getProductCatsMenuHTML()
	{
		global $shop;
		$items = $shop->getCats();
		if($items)
		{
			$output .= '<ul>';
			foreach($items as $item)
			{
				$style = ' style="background-image:url('.SYSICONS_URL.'treemenu/brands_16.png)" ';
				$output .= '<li id="cat_'.$item->getId().'" class="'.$li_class.' leaf" '.$state.' rel="product_cat">';
				$output .= '<a '.$style.' href="?con='.intval($_REQUEST['con']).'&amp;cat='.$item->getId().'">';
				$output .= $item->getTitle();
				$output .= '</a>';
				$output .= '</li>';	
			}
			$output .= '</ul>';
		}
		return $output;
	}
	
	function uploadProductImage($file, $vid=0)
	{
		global $shop;
		if(isset($shop->CurrentProduct))
		{
			$imageClass = new Image();
			global $thumb;
			
			if($imageClass->image_valid($file['type']) && ($file['name'] != "") && (count($thumb['PRODUCT']) > 0))
			{
				$type = $file['type'];
				$temp_name = $file["name"];
				$extension = substr($temp_name,-3);
				$filename = md5(uniqid());
				$new_name = $filename.'.'.$extension;
				
				move_uploaded_file($file["tmp_name"], PRODUCT_PATH.$new_name);
				
				$imageClass->resizePhoto(PRODUCT_PATH.$new_name, $type, $thumb['PRODUCT'][0]['MAXW'], $thumb['PRODUCT'][0]['MAXH']);
				$daName = $new_name;
				$i=0;
				$j=0;
				foreach($thumb['PRODUCT'] as $tmb)
				{
					if($j > 0)
					{
						if($i == 0)
						{ 
							$new_name = $daName; 
							$i = 1;
						}
						else
						{ $new_name = $tmb['MAXW'].'_'.$daName; }
						
						if(is_file(PRODUCT_PATH.$daName))
						{
							if (copy(PRODUCT_PATH.$daName, PRODUCT_PATH.'thumbs/'.$new_name)) 
							{
								if($tmb['RESIZING_TYPE'] == 1)
								{ $imageClass->makeIcons_MergeCenter(PRODUCT_PATH.'thumbs/'.$new_name, PRODUCT_PATH.'thumbs/'.$new_name, $tmb['MAXW'], $tmb['MAXH']); }
								else
								{ $imageClass->resizePhoto(PRODUCT_PATH.'thumbs/'.$new_name, $type, $tmb['MAXW'], $tmb['MAXH']); }
							}
						}
					}
					$j++;
				}
				
				if(is_file(PRODUCT_PATH.$daName))
				{
					$default = 1;
					$select = 'SELECT id FROM '.DB_PERFIX.'shop_images WHERE product_id='.$shop->CurrentProduct->getId().' LIMIT 1;';
					$result = mysql_query($select);
					if(mysql_num_rows($result) > 0)
					{ 
						while($row = mysql_fetch_array($result))
						{
							if($row['id'] > 0)
							{ $default = 0; }
						}
					}
					
					$insert = 'INSERT INTO '.DB_PERFIX.'shop_images (`id`, `product_id`, `variation_id`, `image`, `default`) ';
					$insert .= ' VALUES (NULL, '.$shop->CurrentProduct->getId().', '.$vid.', "'.$daName.'", '.$default.');';
					$result = mysql_query($insert);
					return $result;
				}
				
				$this->JsActionRun = ' jQuery(".tabs").tabs({ selected: 2 }); ';
			}
		}
	}
}
?>